package com.feng.demo.jakartacommons.mina.codec;

import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;

import org.apache.log4j.Logger;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;
import org.apache.mina.filter.codec.demux.MessageDecoder;
import org.apache.mina.filter.codec.demux.MessageDecoderResult;


public class InfoMessageDecoder implements MessageDecoder {
	private static Logger logger = Logger.getLogger(InfoMessageDecoder.class);
	private Charset charset;

	public InfoMessageDecoder(Charset charset) {
		this.charset = charset;
	}

	@Override
	public MessageDecoderResult decodable(IoSession session, IoBuffer in) {
		if (in.remaining() < 6) {
			return MessageDecoderResult.NEED_DATA;
		}
		short tag = in.getShort();
		if (tag == (short) 0x0001 || tag == (short) 0x8001) {
			logger.info("请求标识符：" + tag);
		} else {
			logger.error("未知的解码类型....");
			return MessageDecoderResult.NOT_OK;
		}
		int len = in.getInt();
		if (in.remaining() < len) {
			return MessageDecoderResult.NEED_DATA;
		}
		return MessageDecoderResult.OK;
	}

	@Override
	public MessageDecoderResult decode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {
		logger.info("解码: " + in.toString());
		CharsetDecoder decoder = charset.newDecoder();
		short tag = in.getShort();
		int len = in.getInt();
		byte[] temp = new byte[len];
		in.get(temp);

		IoBuffer buf = IoBuffer.allocate(100).setAutoExpand(true);
		buf.put(temp);
		buf.flip();

		InfoXml ix = new InfoXml();
		String xml = buf.getString(len, decoder);

		ix.setXml(xml);
		out.write(ix);
		return MessageDecoderResult.OK;
	}

	@Override
	public void finishDecode(IoSession session, ProtocolDecoderOutput out) throws Exception {
	}
}
